package org.jiucai.cas.log.service;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.jiucai.appframework.base.spring.helper.SpringHelper;
import org.jiucai.appframework.base.util.AppHolder;
import org.jiucai.appframework.base.util.CommonUtil;
import org.jiucai.appframework.base.util.IpUtil;
import org.jiucai.appframework.common.util.LogUtil;
import org.jiucai.appframework.common.util.Logs;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcOperations;

import org.jiucai.cas.auth.util.UserUtil;
import org.jiucai.cas.data.OpType;
import org.jiucai.cas.domain.AppLog;
import org.jiucai.cas.domain.UserInfo;

/**
 * 记录操作日志
 * 
 * @author zhaidw
 * 
 */
public class LogService {

	private static Logs log = LogUtil.getLog(LogService.class);

	public LogService() {

	}

	private static SimpleJdbcOperations getSimpleJdbcTemplate(
			HttpServletRequest request) {

		return SpringHelper.getSimpleJdbcTemplate(request);
	}

	public static void log(OpType opType, String opContent) {
		
		HttpServletRequest request = AppHolder.getRequest();

		String ip = IpUtil.getIp(request);
		String userAgent = request.getHeader("User-Agent");

		String userName = "";
		
		UserInfo user = UserUtil.getUser();
		if(null != user){
			userName = user.getLoginName();
		}
		
		AppLog appLog = new AppLog();
		appLog.setIp(ip);
		appLog.setUserAgent(userAgent);
		appLog.setOpTime(new Date());
		appLog.setOpType(String.valueOf(opType));
		appLog.setOpContent(opContent);
		appLog.setUserName(userName);

		try {
			Boolean isSaved = saveLog(appLog, request);
			if (!isSaved) {
				log.error("opLog save failed .");
			}else{
				log.info(userName + " 登录日志已保存。");
			}

		} catch (Exception e) {
			log.error("opLog save failed: ", e);
		}

	}

	private static Boolean saveLog(AppLog appLog, HttpServletRequest request) {

		if (null == appLog) {
			return false;
		}

		SimpleJdbcOperations template = getSimpleJdbcTemplate(request);

		Long logId = template
				.queryForLong("select seq_app_log.nextval from dual");

		appLog.setLogId(logId);

		StringBuffer sql = new StringBuffer();

		sql.append(" insert into app_log ");
		sql.append(" (log_id, user_name, op_time, ip, user_agent, op_type, op_content) ");
		sql.append("values ( ");
		sql.append(" :logId, :userName, :opTime, :ip, :userAgent, :opType, :opContent");
		sql.append(" )");

		SqlParameterSource source = new BeanPropertySqlParameterSource(appLog);
		int updateCount = template.update(sql.toString(), source);

		return updateCount > 0 ? true : false;

	}

	public static Long listLogCount(AppLog query, HttpServletRequest request) {
		if (null == query) {
			return 0L;
		}

		SimpleJdbcOperations template = getSimpleJdbcTemplate(request);

		StringBuffer sql = new StringBuffer();

		sql.append("  select  ");
		sql.append("  count(*) as ct");
		sql.append("  from app_log ");
		sql.append("  where  user_name = :userName ");
		sql.append("    order by log_id desc ");

		return template.queryForLong(sql.toString(),
				new BeanPropertySqlParameterSource(query));

	}

	public static List<AppLog> listLog(Long page, Long pageSize, AppLog query,
			HttpServletRequest request) {

		SimpleJdbcOperations template = getSimpleJdbcTemplate(request);

		StringBuffer sql = new StringBuffer();

		sql.append("  select  ");
		sql.append("  log_id, user_name, op_time, ip, user_agent, op_type, op_content ");
		sql.append("  from app_log ");
		sql.append("  where  user_name = :userName ");
		sql.append("    order by log_id desc ");

		String pageSQL = CommonUtil.getPagedSQL(sql.toString(), page, pageSize);

		// 定义返回的bean类型
		BeanPropertyRowMapper<AppLog> mapper = new ParameterizedBeanPropertyRowMapper<AppLog>();
		mapper.setMappedClass(AppLog.class);

		// 定义SQL 绑定参数值
		SqlParameterSource param = new BeanPropertySqlParameterSource(query);

		// 使用 PreparedStatement 进行查询
		List<AppLog> list = template.query(pageSQL, mapper, param);

		return list;

	}

	public static void main(String[] args) {
		OpType opType = OpType.create;

		System.out.println(OpType.create == opType);

		System.out.println(String.valueOf(opType));

	}
}
